<script>
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin';
import { getGoodsList, getPointsExchangeRatio } from '@/api/mall.js';
import slFilter from "@/mall_subpages/components/sl-filter/sl-filter.vue";

export default {
  name: "integralZone",
  components: { slFilter },
  mixins: [ZPMixin],
  data() {
    return {
      loading: false,
      keyword: "", // 搜索关键词
      products: [], // 商品列表
      searchParams: {
        Index: 1,
        Size: 10,
        Tags: "", // 标签ID
        ProductName: "", // 搜索关键词
        PurchaseMethod: "1,2" // 积分购买方式
      },
      filterList: [
        {
          title: '积分',
          key: 'ShowPrice',
          isDrow: false,
          isSort: true,
          reflexTitle: true,
          sort: 'desc',
          detailList: [],
        }
        // {
        //   'title': '价格',
        //   'key': 'ShowPrice',
        //   'isDrow': true,
        //   'isSort': true,
        //   'reflexTitle': true,
        //   'detailList': [
        //     {
        //       'title': '全部',
        //       'value': ""
        //     },
        //     {
        //       'title': '0-100积分',
        //       'value': '0,100'
        //     },
        //     {
        //       'title': '100-500积分',
        //       'value': '100,500'
        //     },
        //     {
        //       'title': '500-1000积分',
        //       'value': '500,1000'
        //     },
        //     {
        //       'title': '1000积分以上',
        //       'value': '1000,999999'
        //     }
        //   ]
        // },
        // {
        //   'title': '排序',
        //   'key': 'SortBy',
        //   'isDrow': false,
        //   'isSort': true,
        //   'sort': 'desc',
        //   'reflexTitle': true,
        //   'detailList': []
        // }
      ],
      IsDesc: {},
      zoneName: "", // 分区名称
      pointsRatio: 1, // 积分兑换比例
    }
  },
  onLoad(options) {
    if (options.id) {
      this.searchParams.Tags = options.id;
    }
    if (options.title) {
      this.zoneName = decodeURIComponent(options.title);
      uni.setNavigationBarTitle({
        title: this.zoneName || '积分商城'
      });
    }
    // 获取积分兑换比例
    this.getPointsRatio();
  },
  methods: {
    // 获取积分兑换比例
    async getPointsRatio() {
      try {
        const res = await getPointsExchangeRatio();
        const data = res.Data;
        this.pointsRatio = data.PointToCNYRatio;
        console.log('获取到积分比例:', this.pointsRatio);
      } catch (error) {
        console.error('获取积分比例失败:', error);
        this.pointsRatio = 1;
      }
    },

    // 商品列表查询
    async queryList(pageNo, pageSize) {
      try {
        this.loading = true;
        this.searchParams.Index = pageNo;
        this.searchParams.Size = pageSize;
        this.searchParams.ProductName = this.keyword;

        const { Data } = await getGoodsList(this.searchParams);

        this.loading = false;
        this.$refs.paging.complete(Data || []);
      } catch (error) {
        console.error("获取商品列表失败:", error);
        this.loading = false;
        this.$refs.paging.complete(false);
      }
    },

    // 搜索
    onSearch() {
      this.$refs.paging.reload();
    },

    // 点击商品
    goToProductDetail(id) {
      uni.navigateTo({
        url: `/mall_subpages/goods/index?id=${id}&type=3&integral=true`
      });
    },

    // 处理筛选结果
    handleResult(result) {
      console.log(result);
      this.IsDesc = result;
      // if (Object.keys(result).length > 0) {
      //   const [type, value] = Object.entries(result)[0];
      //   this.searchParams[type] = value;
      // }
      const [type, value] = Object.entries(result)[0];
      this.searchParams.FiledOrder = `${type} ${value}`;
      this.$refs.paging.reload();
    }
  }
}
</script>

<template>
  <view class="zone-container">
    <z-paging
        ref="paging"
        v-model="products"
        @query="queryList"
        :refresher-enabled="true"
        :auto-show-back-to-top="true"
        :auto-scroll-to-top-when-reload="true"
        :show-scrollbar="false"
        :paging-style="{height: '100%'}"
    >
      <!-- 顶部搜索区域 -->
      <template #top>
        <view class="search-container">
          <view class="search-box">
            <view class="search-input-wrapper">
              <u-icon name="search" color="#999" size="30"></u-icon>
              <input
                type="text"
                v-model="keyword"
                placeholder="搜索商品"
                confirm-type="search"
                @confirm="onSearch"
              />
              <u-icon name="close" color="#999" size="30" v-if="keyword" @click="keyword = ''; onSearch()"></u-icon>
            </view>
            <view class="search-btn" @click="onSearch">搜索</view>
          </view>
          <!-- 筛选区域 -->
          <view class="filter-section">
            <sl-filter
                :independence="true"
                :topFixed="false"
                :tab-height="34"
                titleColor="#333"
                :isDesc="IsDesc"
                themeColor="#dab34c"
                :menuList.sync="filterList"
                @result="handleResult">
            </sl-filter>
          </view>
        </view>
      </template>

      <!-- 商品列表 -->
      <view class="product-grid">
        <view
          class="product-item"
          v-for="(item, index) in products"
          :key="index"
          @click="goToProductDetail(item.Id)"
        >
          <view class="product-image">
            <image :src="item.Img" mode="aspectFill"></image>
          </view>
          <view class="product-info">
            <view class="product-title">{{item.Name || '商品名称'}}</view>
            <view class="product-price">
              <text class="price-value">{{ Math.ceil(item.ShowPrice * pointsRatio) || 0 }}</text>
              <text class="price-unit">积分</text>
              <text class="price-original" v-if="item.OriginalPrice">¥{{item.OriginalPrice}}</text>
            </view>
          </view>
          <view class="exchange-time" v-if="item.ExchangeTime">
            {{item.ExchangeTime}}
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<style scoped lang="scss">
.zone-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #F5F6F7;
}

/* 搜索区域样式 */
.search-container {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-box {
  display: flex;
  align-items: center;

  .search-input-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #F5F6F7;
    border-radius: 40rpx;
    padding: 10rpx 20rpx;
    height: 70rpx;

    input {
      flex: 1;
      height: 70rpx;
      font-size: 28rpx;
      color: #333;
      margin: 0 16rpx;
    }
  }

  .search-btn {
    margin-left: 20rpx;
    font-size: 28rpx;
    color: #333;
    height: 70rpx;
    line-height: 70rpx;
    padding: 0 20rpx;
  }
}

/* 筛选区域样式 */
.filter-section {
  background-color: #ffffff;
  padding: 10rpx 0;
  /deep/ .select-tab-item {
    justify-content: flex-start !important;
  }
}

/* 商品列表样式 */
.product-grid {
  padding: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.product-item {
  width: calc(50% - 10rpx);
  background-color: #ffffff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

  .product-image {
    width: 100%;
    height: 320rpx;
    background-color: #f0f0f0;

    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .product-info {
    padding: 20rpx;

    .product-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .product-price {
      display: flex;
      align-items: baseline;

      .price-value {
        font-size: 32rpx;
        color: #D4AF7A;
        font-weight: bold;
      }

      .price-unit {
        font-size: 24rpx;
        color: #999;
        margin-left: 5rpx;
      }

      .price-original {
        font-size: 22rpx;
        color: #999;
        text-decoration: line-through;
        margin-left: auto;
      }
    }
  }

  .exchange-time {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #FFE4BD;
    color: #D4AF7A;
    text-align: center;
    font-size: 24rpx;
    padding: 10rpx;
  }
}

/* 加载动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.product-item {
  animation: fadeIn 0.5s ease-out;
}
</style>
